package com.primaryedu.ui.app.growstep;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.ClassDynamicBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.ui.BaseAppCompatActivity;
import com.primaryedu.ui.app.nicedialog.BaseNiceDialog;
import com.primaryedu.ui.app.nicedialog.DialogCallBackUtils;
import com.primaryedu.ui.app.nicedialog.DialogSureCallBack;
import com.primaryedu.ui.app.nicedialog.MyCustomDialog;
import com.primaryedu.widget.PullToRefreshView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thomas on 2018/3/1.
 */

public class MyClassDynamicActivity extends BaseAppCompatActivity implements View.OnClickListener, PullToRefreshView.OnHeaderRefreshListener,
        PullToRefreshView.OnFooterRefreshListener, MydynamicAdapter.DeleteMyCallback, DialogSureCallBack {

    private ListView listView;
    private int page = 1;
    private PullToRefreshView pullToRefreshView;
    private List<ClassDynamicBean.DataBean.ListBean> classdynamicLists = new ArrayList<>();
    private List<ClassDynamicBean.DataBean.ListBean> classdynamictempList = new ArrayList<>();
    private boolean fistenter = true;
    private MydynamicAdapter classdynamicAdapter;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != classdynamictempList && classdynamictempList.size() != 0) {
                        classdynamicAdapter = new MydynamicAdapter(MyClassDynamicActivity.this, classdynamictempList, MyClassDynamicActivity.this);
                        listView.setAdapter(classdynamicAdapter);
                    }
                    break;
                case 1002:
                    if (classdynamictempList != null && classdynamictempList.size() != 0) {
                        classdynamicAdapter.updateClassdynamicView(classdynamictempList);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private ClassDynamicBean.DataBean.ListBean cd;
    private String userId;
    private String isClassDynamic;
    private Integer deletePosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_class_dynamic);

        init();
        getclassDynamic(fistenter);
    }


    private void init() {
        Intent intent = getIntent();
        userId = intent.getStringExtra("userId");
        isClassDynamic  = intent.getStringExtra("boolean");
        ((TextView) findViewById(R.id.title)).setText("我的动态");
        findViewById(R.id.back).setOnClickListener(this);
        listView = (ListView) this.findViewById(R.id.listView);


//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
//                                    long arg3) {
//                VotelistBean.DataBean.ListBean vb = votetempList.get(position);
//                Intent intent = new Intent(VoteActivity.this,VoteDetailsActivity.class) ;
//                intent.putExtra("id",vb.getId());
//
//                startActivity(intent);
//            }
//        });


        pullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_class_dynamic;
    }

    @Override
    protected void initView() {
        DialogCallBackUtils.setCallBack(this);
    }

    @Override
    protected void initData() {

    }

    private void getclassDynamic(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        page = 1;

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.classdynamicList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=masterboxlist=======" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                classdynamicLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<ClassDynamicBean.DataBean.ListBean>>() {
                                        }.getType());
                                classdynamictempList.clear();
                                classdynamictempList.addAll(classdynamicLists);
                                handler.sendEmptyMessage(1001);

                                System.out.println("leaveLists==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                if (isClassDynamic.equals("0")) {// “0”是本人ID
                    map.put("userId", GlobalData.getUserId(MyClassDynamicActivity.this));
                }else if (isClassDynamic.equals("1")){//“1”是从班级动态中点击的用户ID
                    map.put("userId", userId);
                }
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    private void requestmoreclassdynamicList() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.classdynamicList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=masterboxlist=======" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {

                                String data = json.getString("data");
                                if (data.contains("list")) {
                                    JSONObject listObj = new JSONObject(data);
                                    String listStr = listObj.getString("list");

                                    classdynamicLists = new Gson().fromJson(listStr,
                                            new TypeToken<List<ClassDynamicBean.DataBean.ListBean>>() {
                                            }.getType());
//
                                    classdynamictempList.addAll(classdynamicLists);
                                    handler.sendEmptyMessage(1002);
                                } else {
                                    showToast("已经加载完全部数据！");
                                }
//								System.out.println("leaveLists=="+listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                if (isClassDynamic.equals("0")) {// “0”是本人ID
                    map.put("userId", GlobalData.getUserId(MyClassDynamicActivity.this));
                }else if (isClassDynamic.equals("1")){//“1”是从班级动态中点击的用户ID
                    map.put("userId", userId);
                }
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    private void deletedynamice(final ClassDynamicBean.DataBean.ListBean cd, final int deletePosition) {
        showLoading("删除中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.deleteClassdynamic,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=voteuser=======" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                showToast("删除成功");
                                classdynamictempList.remove(deletePosition);
                                classdynamicAdapter.notifyDataSetChanged();
                            } else if (result == 0) {
                                showToast("删除失败，请重新删除！");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("删除失败，请重新删除！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", cd.getId());
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            default:
                break;
        }
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                requestmoreclassdynamicList();
                pullToRefreshView.onFooterRefreshComplete();

            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                getclassDynamic(false);
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(MyClassDynamicActivity.this, "数据刷新完成!", Toast.LENGTH_LONG).show();
            }

        }, 1500);
    }

    @Override
    public void deletemyclick(View v) {
        deletePosition = (Integer) v.getTag();
        cd = classdynamictempList.get((Integer) v.getTag());
        Log.i("yy", "deleteclick: =====" + cd.getId());
        MyCustomDialog.newInstance("deletedynamic")
                .setMargin(60)
                .setOutCancel(false)
                .show(getSupportFragmentManager());

    }

    @Override
    public void SureClick(String type, BaseNiceDialog dialog) {
        if ("deletedynamic".equals(type)) {
            deletedynamice(cd, deletePosition);
        }
        dialog.dismiss();
    }
}
